<!--
/**
* @name OperateForm
* @description ** 新增编辑用户
* @author mdong
* @date 2020-05-12
* @param {**} ** **
* @example ***
*/
-->
<template>
  <div calss="operate-form"
       id="um-modal">
    <a-modal :title="title"
             :okButtonProps="{props:{icon:'save'}}"
             :cancelButtonProps="{props:{icon:'close-circle'}}"
             :wrapClassName="isDetails?'modal-box modal-hidden-footer':'modal-box'"
             :maskClosable="false"
             :width="800"
             :visible="operateVisible"
             :confirm-loading="confirmLoading"
             @ok="handleSubmit"
             okText="提交"
             @cancel="handleVisible"
             :destroyOnClose="true">
      <form-loading :formLoadingVisible="formLoadingVisible"></form-loading>
      <!-- <h3 class="form-title"> 新增组织 </h3> -->
      <a-form-model ref="ruleForm"
                    :model="form"
                    :hideRequiredMark="isDetails"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="登录账号"
                               prop="username">
              <a-input allowClear
                       v-show="!isDetails"
                       :disabled="optType === 'edit'"
                       placeholder="请输入登录账号"
                       v-model="form.username"
                       :maxLength="20">
              </a-input>
              <span v-show="isDetails">{{form.username}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="用户姓名"
                               prop="name">
              <a-input allowClear
                       v-show="!isDetails"
                       placeholder="请输入用户姓名"
                       v-model="form.name"
                       :maxLength="20">
              </a-input>
              <span v-show="isDetails">{{form.name}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="所属区域"
                               prop="orgIds">
              <!-- <a-input disabled
                       v-model="form.parentName">
              </a-input> -->
              <a-cascader v-show="!isDetails"
                          v-model="form.orgIds"
                          placeholder="请选择所属区域"
                          :options="treeData"
                          :show-search="{ filterAreaData }"
                          :field-names="{ label: 'name', value: 'id', children: 'childrenList' }"
                          change-on-select />
              <span v-show="isDetails">{{getAreaName(treeData, form.orgIds?form.orgIds[form.orgIds.length - 1]+',':'')}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="邮箱"
                               prop="email">
              <a-input allowClear
                       v-show="!isDetails"
                       placeholder="请输入邮箱"
                       v-model="form.email"
                       :maxLength="20">
              </a-input>
              <span v-show="isDetails">{{form.email || '无'}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="电话号码"
                               prop="phone">
              <a-input allowClear
                       v-show="!isDetails"
                       placeholder="请输入电话号码"
                       v-model="form.phone"
                       :maxLength="13">
              </a-input>
              <span v-show="isDetails">{{form.phone || '无'}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="性别"
                               prop="sex">
              <a-select v-model="form.sex"
                        v-show="!isDetails"
                        placeholder="请选择性别"
                        style="width: 100%"
                        allowClear>
                <a-select-option v-for="(item,index) in sexConst "
                                 :key="index"
                                 :value="item.value"> {{item.name}}</a-select-option>
              </a-select>
              <span v-show="isDetails">{{convertConstName(sexConst, form.sex)}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16"
               v-show="isDetails">
          <a-col :span="24">
            <a-form-model-item :label-col="{span:3}"
                               label="用户角色">
              <span>{{currUserRole || '无'}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getDictData } from '@/request/api/common'
import { regexConstants, validators } from '@/utils/validate'
import { FormModel, Modal, Row, Col, Input, Select, Cascader } from 'ant-design-vue'
import FormLoading from '@/components/FormLoading'
import { convertConstName } from '@/utils/filter'
import { getUserById, checkUserPhone, checkUserUserName, getCurrentRole } from '@/request/api/permissionManagement/user/user'
export default {
  name: 'OperateForm',
  components: {
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AModal: Modal,
    FormLoading,
    ARow: Row,
    ACol: Col,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    ACascader: Cascader
  },
  props: {
    // 当前点击树节点
    currSelTreeNode: {
      type: Object,
      required: true
    },
    // 左侧树数据
    treeData: {
      type: Array,
      required: true
    },
    // 提交按钮loading状态
    confirmLoading: {
      type: Boolean,
      required: true
    },
    // 是否打开新增和编辑抽屉
    operateVisible: {
      type: Boolean,
      required: true
    },
    optType: {
      type: String,
      default: 'add'
    },
    getAreaName: {
      type: Function
    },
    // 新增和编辑抽屉数据
    operateData: {
      type: Object,
      required: true,
      default: function () {
        return {
          orgIds: {
            type: Array,
            default: []
          },
          name: {
            type: String,
            default: ''
          },
          username: {
            type: String,
            default: ''
          },
          phone: {
            type: String,
            default: ''
          },
          email: {
            type: String,
            default: ''
          },
          sex: {
            type: String,
            default: ''
          }
        }
      }
    }
  },
  data () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      form: {
        name: '',
        parentName: '',
        username: '',
        phone: '',
        email: '',
        sex: '',
        orgIds: undefined
      },
      rules: {
        orgIds: [
          { required: true, message: '请选择组织', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              console.log('触发checkUserUserName...')
              checkUserUserName({
                username: this.form.username,
                id: this.form.id
              }).then((res) => {
                if (res.code === '0') {
                  callback()
                } else {
                  callback(new Error(res.msg))
                }
              }).catch(() => {
                callback(new Error('检查登录账号失败'))
              })
            },
            trigger: 'none'
          }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {
            pattern: regexConstants.phone,
            validator: validators.validate,
            message: '请输入合法的手机号码',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              console.log('触发checkUserPhone...')
              checkUserPhone({
                phone: this.form.phone,
                id: this.form.id || ''
              }).then((res) => {
                if (res.code === '0') {
                  callback()
                } else {
                  callback(new Error(res.msg))
                }
              }).catch(() => {
                callback(new Error('检查手机号失败'))
              })
            },
            trigger: 'none'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: regexConstants.email,
            validator: validators.validate,
            message: '请输入合法的邮箱',
            trigger: 'blur'
          }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      },
      // 标题
      title: '',
      // 表单加载loading
      formLoadingVisible: false,
      sexConst: [],
      currUserRole: ''
    }
  },
  watch: {
    // 监听抽屉打开关闭
    operateVisible: {
      async handler (newV, oldV) {
        // 打开抽屉
        if (newV) {
          // 新增
          this.formLoadingVisible = true
          if (this.optType === 'add') {
            this.title = '新增用户'
            this.form.parentName = this.operateData.parentName
            for (const key in this.operateData) {
              if (key !== 'parentName' && key !== 'orgId' && key !== 'orgIds') {
                this.operateData[key] = undefined
              }
            }
            this.form = Object.assign({}, this.operateData)
            await this.getDictDataList()
          }
          // 编辑
          if (this.optType === 'edit' || this.optType === 'view') {
            if (this.optType === 'view') {
              this.title = '用户详细'
              this.form = Object.assign({}, this.operateData)
              await Promise.all([this.getDictDataList(), this.getUserById(), this.getCurrentRole()])
            } else {
              this.title = '编辑用户'
              this.form = Object.assign({}, this.operateData)
              await Promise.all([this.getDictDataList(), this.getUserById()])
            }
            for (const key in this.form) {
              this.form[key] = this.form[key] || undefined
            }
          }
          const ids = this.form.orgId.split(',')
          ids.pop()
          this.form.orgIds = ids
          this.formLoadingVisible = false
        } else {
          this.form = Object.assign(this.form, {
            name: '',
            parentName: '',
            username: '',
            phone: '',
            email: '',
            sex: '',
            orgIds: [],
            orgId: '',
            id: ''
          })
        }
      }
    }
  },
  computed: {
    isDetails () {
      return this.optType === 'view'
    }
  },
  mounted () {
  },
  beforeDestroy () {
    this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
    for (const key in this.operateData) {
      this.operateData[key] = ''
    }
  },
  created () {
    this.getDictDataList()
  },
  methods: {
    convertConstName,
    // 过滤级联数据
    filterAreaData (inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    // 获取用户详细
    async getUserById () {
      await getUserById({ id: this.form.id }).then((res) => {
        if (res.code === '0') {
          this.form = Object.assign({ orgIds: [] }, res.data)
          this.form.parentName = this.operateData.parentName
        }
      })
    },
    // 获取用户角色
    async getCurrentRole () {
      await getCurrentRole({ id: this.form.id }).then((res) => {
        if (res.code === '0') {
          this.currUserRole = res.data.map(({ name }) => {
            return name
          }).join()
        }
      })
    },
    // 获取数据字典
    async getDictDataList () {
      const params = 'Y-0B-002'
      await getDictData(params).then((res) => {
        if (res.code === '0') {
          const data = res.data
          this.sexConst = data['Y-0B-002']
        }
      })
    },
    handleSubmit () {
      this.$emit('update:confirmLoading', true) // 检查登录用户和手机号
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = { ...this.form }
          form.orgId = form.orgIds.join() + ','
          delete form.orgIds
          this.$emit('handleSubmit', form)
        } else {
          this.$emit('update:confirmLoading', false)
          this.$message.error('请完善信息！')
          return false
        }
      })
    },
    // 关闭抽屉
    handleVisible () {
      this.$emit('handleVisible', false)
    }
  }
}
</script>
<style lang="scss">
.form-title {
  font-size: 16px;
  border-bottom: 1px solid #e8e8e8;
  height: 40px;
  margin-bottom: 20px;
}
</style>
